package com.xiaoyu.im.request.flow;

import androidx.annotation.Nullable;

import com.xiaoyu.im.datamodel.common.IMConstant;
import com.xiaoyu.im.datamodel.MessageStatus;
import com.xiaoyu.im.request.MessageRequest;

import in.srain.cube.util.CLog;

import static com.xiaoyu.im.datamodel.MessageStatus.INIT;

public class RequestFlow {

    private static FlowAction sCheckAction = new BaseCheckAction();
    private static FlowAction sPrepareAction = new BasePrepareAction();
    private static FlowAction sSendAction = new BaseSendAction();
    private static FlowAction sSuccessAction = new BaseSuccessAction();
    private static FlowAction sFailureAction = new BaseFailureAction();

    public static void setCheckAction(BaseCheckAction checkAction) {
        sCheckAction = checkAction;
    }

    public static void setPrepareAction(BasePrepareAction prepareAction) {
        sPrepareAction = prepareAction;
    }

    public static void setSendAction(BaseSendAction sendAction) {
        sSendAction = sendAction;
    }

    public static void setSuccessAction(BaseSuccessAction successAction) {
        sSuccessAction = successAction;
    }

    public static void setFailureAction(BaseFailureAction failureAction) {
        sFailureAction = failureAction;
    }

    public void start(MessageRequest request) {
        request.setStatus(INIT);
        evolveToNextStatus(request);
    }

    public static void evolveToNextStatus(MessageRequest request) {
        CLog.d(IMConstant.LOG_TAG, "evolveToNextStatus: %s", request);
        FlowAction step = getNextStatus(request);
        if (step != null) {
            step.exec(request);
        }
    }

    @Nullable
    private static FlowAction getNextStatus(MessageRequest request) {
        final int status = request.getStatus();
        if (status == INIT) {
            return sCheckAction;
        }
        if (status == MessageStatus.CHECKED) {
            return sPrepareAction;
        }
        if (status == MessageStatus.PREPARED) {
            return sSendAction;
        }
        if (status == MessageStatus.SUCCESS) {
            return sSuccessAction;
        }
        if (MessageStatus.isFailedStatus(status)) {
            return sFailureAction;
        }
        return null;
    }
}
